package net.oschina.j2chain;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.Serializable;

/**
 * 区块定义
 */
public class Block implements Serializable {

    private int index;
    private String hash;
    private String prevHash;
    private byte[] data;
    private long timestamp;

    public Block(int index, String prevHash, byte[] data) {
        this.index = index;
        this.prevHash = prevHash;
        this.data = new byte[data.length];
        System.arraycopy(this.data, 0, data, 0 , data.length);
        this.timestamp = System.currentTimeMillis();
        this.hash = hash();
    }

    /**
     * 生成区块哈希
     * @return
     */
    private String hash() {
        String hashStr = index + '#' + prevHash + '#' + '#' + timestamp;
        byte[] hashData = hashStr.getBytes();
        byte[] wholeData = new byte[hashData.length + data.length];
        System.arraycopy(hashData,0,wholeData,0,hashData.length);
        System.arraycopy(data, 0, wholeData, hashData.length, data.length);
        return DigestUtils.sha256Hex(wholeData);
    }

    public String getHash() {
        return hash;
    }

    public int getIndex() {
        return index;
    }

    public String getPrevHash() {
        return prevHash;
    }

    public byte[] getData() {
        return data;
    }

    public long getTimestamp() {
        return timestamp;
    }

}
